import { defineComponent, reactive, ref } from 'vue'
import {
  FormRules,
  NButton,
  NDataTable,
  NForm,
  NFormItem,
  NInput,
  NRadio,
  NRadioGroup,
  NSpace
} from 'naive-ui'
import { useColumns } from './use-columns'
import { useTable } from './use-table'
import styles from './index.module.scss'
import { createTableReq } from '@/service/modules/data-manage'

const CreateTableTab = defineComponent({
  name: 'CreateTableTab',
  props: {
    dsType: {
      type: String,
      required: true
    },
    datasourceId: {
      type: Number,
      required: true
    },
    dsName: {
      type: String,
      required: true
    },
    dbName: {
      type: String,
      required: true
    },
    databaseId: {
      type: Number,
      required: true
    }
  },
  setup() {
    const { state, createTableEntity, getDataTypeOptions, onOperationClick } =
      useTable()
    const { fieldColumnsRef, indexColumnsRef } = useColumns(
      state,
      onOperationClick
    )
    const rules: FormRules = {
      tableName: {
        trigger: ['input', 'blur'],
        required: true,
        validator() {
          if (createTableEntity.tableInfo.tableName === '') {
            return new Error(window.$t('dataManage.tableNameTips'))
          }
        }
      },
      ddl: {
        trigger: ['input', 'blur'],
        required: true,
        validator() {
          if (createTableEntity.ddl === '') {
            return new Error(window.$t('dataManage.ddlTips'))
          }
        }
      }
    }
    const createTableBtnDisableRef = ref(false)
    return {
      state,
      getDataTypeOptions,
      fieldColumnsRef,
      indexColumnsRef,
      createTableEntity,
      rules,
      createTableBtnDisableRef
    }
  },
  created() {
    this.getDataTypeOptions(this.databaseId)
    this.createTableEntity.datasourceId = this.datasourceId
    this.createTableEntity.dbName = this.dbName
  },
  methods: {
    addNewField() {
      this.createTableEntity.tableInfo.columns.push({
        columnName: 'new_column',
        dataType: this.state.dataTypeOptions[0].value as string,
        args: '',
        isNotNull: false,
        defVal: '',
        isPrimkey: false,
        isPartition: false,
        columnComment: '',
        previewData: ''
      })
    },
    addNewIndex() {
      this.createTableEntity.tableInfo.indexs.push({
        indexName: 'new_index',
        columns: '',
        isUnique: false
      })
    },
    async createTable() {
      this.createTableBtnDisableRef = true
      //将预览数据添加到data请求体上
      if (this.createTableEntity.mode === 'visual') {
        const previewData = {}
        this.createTableEntity.tableInfo.columns.forEach((item) => {
          previewData[item.columnName] = item.previewData
        })
        this.createTableEntity.previewData = JSON.stringify(previewData)
      }
      await createTableReq(this.createTableEntity).catch(() => {
        this.createTableBtnDisableRef = false
      })
      this.createTableBtnDisableRef = false
    },
    //判断数据源类型是否支持sql建表
    supportSql(): boolean {
      //目前mysql/hive/oracle支持sql建表
      const supportSqlDs = ['MYSQL', 'HIVE', 'ORACLE']
      if (supportSqlDs.indexOf(this.dsType) !== -1) {
        return false
      }
      return true
    }
  },
  render() {
    return (
      <div class={styles.container}>
        <div class={styles.baseInfo}>
          <NForm
            rules={this.rules}
            label-placement='left'
            require-mark-placement='right-hanging'
            label-width='auto'
          >
            <NFormItem
              path='mode'
              label={window.$t('dataManage.createTableMode')}
            >
              <NRadioGroup v-model:value={this.createTableEntity.mode}>
                <NRadio value='visual'>{window.$t('dataManage.visual')}</NRadio>
                <NRadio value='sql' disabled={this.supportSql()}>
                  SQL
                </NRadio>
              </NRadioGroup>
            </NFormItem>
            <NFormItem
              path='tableName'
              label={window.$t('dataManage.tableName')}
              v-show={this.createTableEntity.mode === 'visual'}
            >
              <NInput
                type='text'
                v-model:value={this.createTableEntity.tableInfo.tableName}
                style='width:200px'
                placeholder={window.$t('dataManage.tableNameTips')}
              />
            </NFormItem>
            <NFormItem
              path='tableComment'
              label={window.$t('dataManage.tableComment')}
              v-show={this.createTableEntity.mode === 'visual'}
            >
              <NInput
                type='text'
                v-model:value={this.createTableEntity.tableInfo.tableComment}
                style='width:200px'
                placeholder={window.$t('dataManage.tableCommentTips')}
              />
            </NFormItem>
            <NFormItem
              path='numPartitions'
              label={window.$t('dataManage.numPartitions')}
              v-show={
                this.createTableEntity.mode === 'visual' &&
                this.dsType === 'KAFKA'
              }
            >
              <NInput
                type='text'
                v-model:value={this.createTableEntity.ddl}
                style='width:80px'
              />
            </NFormItem>
            <NFormItem
              path='ddl'
              label={window.$t('dataManage.createTableDDL')}
              v-show={this.createTableEntity.mode === 'sql'}
            >
              <NInput
                type='textarea'
                v-model:value={this.createTableEntity.ddl}
                placeholder={window.$t('dataManage.createTableDDL')}
                style='height:300px'
              />
            </NFormItem>
            <NFormItem
              path='tableComment'
              label={window.$t('dataManage.applyReason')}
            >
              <NInput
                type='textarea'
                v-model:value={this.createTableEntity.reason}
              />
            </NFormItem>
          </NForm>
        </div>
        <div
          class={styles.fieldInfo}
          v-show={this.createTableEntity.mode === 'visual'}
        >
          <NSpace justify='space-between'>
            <h3>{window.$t('dataManage.tableConstruction')}</h3>
            <NButton
              type='info'
              size='small'
              onClick={this.addNewField}
              style='margin-top:16px'
            >
              {window.$t('dataManage.addField')}
            </NButton>
          </NSpace>
          <NDataTable
            row-class-name='items'
            columns={this.fieldColumnsRef.fieldColumns}
            size='small'
            single-line={false}
            data={this.createTableEntity.tableInfo.columns}
            loading={this.state.loading}
            scrollX={this.fieldColumnsRef.tableWidth}
          />
        </div>
        <div
          class={styles.indexInfo}
          v-show={this.createTableEntity.mode === 'visual'}
        >
          <NSpace justify='space-between'>
            <h3>{window.$t('dataManage.tableIndex')}</h3>
            <NButton
              type='info'
              size='small'
              onClick={this.addNewIndex}
              style='margin-top:16px'
            >
              {window.$t('dataManage.addIndex')}
            </NButton>
          </NSpace>

          <NDataTable
            row-class-name='items'
            columns={this.indexColumnsRef.indexColumns}
            size='small'
            single-line={false}
            data={this.createTableEntity.tableInfo.indexs}
            loading={this.state.loading}
            scrollX={this.indexColumnsRef.tableWidth}
          />
        </div>
        <NSpace justify='center' style='margin-top:10px'>
          <NButton
            type='info'
            onClick={this.createTable}
            disabled={this.createTableBtnDisableRef}
          >
            {window.$t('dataManage.createTable')}
          </NButton>
        </NSpace>
      </div>
    )
  }
})

export default CreateTableTab
